package com.xm.concurrent.base;

import java.util.ArrayList;
import java.util.List;
import java.util.TreeMap;
import java.util.concurrent.TimeUnit;
import java.util.logging.Logger;

/**
 * 4.2 线程优先级
 *
 * @author xiaoming
 * @date 2021-05-18 23:02
 */
public class Priority {

    public static volatile boolean notStart = true;
    public static volatile boolean notEnd = true;

    public static void main(String[] args) throws InterruptedException {
        List<Job> jobs = new ArrayList<Job>();
        for (int i = 0; i < 10; i++) {
            int priority = i < 5 ? Thread.MIN_PRIORITY : Thread.MAX_PRIORITY;
            Job job = new Job(priority);
            jobs.add(job);
            Thread thread = new Thread(job, "Thread : " + i);
            thread.setPriority(priority);
            thread.start();

        }

        notStart = false;
        TimeUnit.SECONDS.sleep(10);
        notEnd = false;

        for (Job job : jobs) {
            System.out.println("Job Priority: " + job.priority + ", Count: " + job.jobCount);
            /*
            // 打印结果:
                Job Priority: 1, Count: 66426
                Job Priority: 1, Count: 66407
                Job Priority: 10, Count: 2148410
                Job Priority: 10, Count: 2146298
             // 这里与书中打印结果不同,书中两个优先级之间 Count 差距不大, 作者是 Mac 系统
             */
        }



    }


    static class Job implements Runnable{
        private int priority;
        private long jobCount;

        @Override
        public void run() {
            while (notStart) {
                Thread.yield(); // 线程让步
            }

            while (notEnd) {
                Thread.yield(); // 线程让步
                jobCount++;
            }

        }

        public Job(int priority) {
            this.priority = priority;
        }
    }

}
